package com.iris.thread.reentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 项目: thinking
 * 包名: com.iris.thread.reentrantLock
 * 作者: victor
 * 日期: 2016年10月31日
 * 说明: ReentrantLockTest
 */
public class ReentrantLockTest {
	
	
/**
 * 
 * 
 * ReentrantLock lock = new ReentrantLock();  
	...........  
	lock.lockInterruptibly();//获取响应中断锁  
	try {  
	      //更新对象的状态  
	      //捕获异常，必要时恢复到原来的不变约束  
	      //如果有return语句，放在这里  
	}finally{  
	    lock.unlock();        //锁必须在finally块中释放  
	}  
 */
	

	private ReentrantLock lock=new ReentrantLock();
	
	public void write(){
		lock.lock();
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
		System.out.println("write ====end");
			
	}
	
	public void read(){
		try {
			System.out.println("read===lockInterruptibly=");
			lock.lockInterruptibly();
			System.out.println("read===lockInterruptibly====end");
//			Thread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("read===InterruptedException=");
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
		System.out.println("read ====end");
	}
	
	public static void main(String[] args) {
		ReentrantLockTest rl = new ReentrantLockTest();
		Thread read = new Thread(new ReentranLockRead(rl),"read");
		Thread write = new Thread(new ReentranLockWrite(rl),"write");
		try {
			System.out.println("main write start");
			write.start();
			System.out.println("main sleep(100);");
			Thread.sleep(100);
			System.out.println("main read start");
			read.start();
			System.out.println("main sleep(1000);");
			Thread.sleep(3000);
			System.out.println("main interrupt");
			read.interrupt();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
	}
}

class ReentranLockRead implements Runnable{

	private ReentrantLockTest rl;
	public ReentranLockRead(ReentrantLockTest rl){
		this.rl=rl;
	}
	@Override
	public void run() {

		rl.read();
		
	}
	
}
class ReentranLockWrite implements Runnable{
	private ReentrantLockTest rl;
	public ReentranLockWrite(ReentrantLockTest rl){
		this.rl=rl;
	}
	@Override
	public void run() {
		rl.write();
		
	}
	
}




